package com.example.kwokg.meishi.Activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.astuetz.PagerSlidingTabStrip;
import com.example.kwokg.meishi.Bean.Title;
import com.example.kwokg.meishi.Constants;
import com.example.kwokg.meishi.Fragments.ContentFragment;
import com.example.kwokg.meishi.LoadJsonTask;
import com.example.kwokg.meishi.MyVpAdapter;
import com.example.kwokg.meishi.R;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.Bmob;

public class MainActivity extends AppCompatActivity {

    private String customColor="#3F51B5";
    private ViewPager mVp;
    private PagerSlidingTabStrip tabs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bmob.initialize(this, Constants.Bmob_APPID);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        //初始化缓存目录
        new File(Constants.APP_ROOTPATH).mkdirs();

        //初始化抽屉和ViewPager
        initDrawer();
        initVp();

        //检测用户是否是登录状态
        hasLogin();

        //处理登录成功事件
        setDrawer();
    }

    private void hasLogin() {
        String username = getSharedPreferences("name", MODE_PRIVATE).getString("name", null);
        Log.i("Tag","hasLogin------"+username+"----------"+this.getClass().getSimpleName());
        inLogin(username);
    }

    private void setDrawer() {
        Intent intent=getIntent();
        //获取登录成功的用户名
        String username=intent.getStringExtra("name");
        if (username!=null){
            //登录信息保存到本地
            SharedPreferences name = getSharedPreferences("name", MODE_PRIVATE);
            SharedPreferences.Editor editor = name.edit();
            editor.putString("name",username).commit();
            inLogin(username);
        }
    }

    private void inLogin(String username) {
        TextView name = (TextView) findViewById(R.id.username);
        LinearLayout ly_dw = (LinearLayout) findViewById(R.id.ly_dw);
        Log.i("Tag","inLogin------"+username+"----------"+this.getClass().getSimpleName());
        if (username!=null){
            //隐藏登录按钮，显示TextView内容
            name.setText(username);
            name.setVisibility(View.VISIBLE);
            ly_dw.setVisibility(View.INVISIBLE);
        }else{
            name.setVisibility(View.GONE);
            ly_dw.setVisibility(View.VISIBLE);
        }
    }

    //对ViewPager的操作
    private void initVp() {
        //滑动条控件
        tabs = (PagerSlidingTabStrip) findViewById(R.id.tabStrip);
        mVp = (ViewPager) findViewById(R.id.vp);

        //解析Json获取分类信息
        new LoadJsonTask(new LoadJsonTask.onGetJsonResultListener() {
            @Override
            public void onGetJsonResult(Object result) {
                //拿到数据后处理数据
                initData((List<Title>) result);
            }
        },Constants.TITLE).execute(Constants.TITLE_URL);
    }

    //设置标题及fragment数据
    private void initData(List<Title> result) {
        List<Title> mData=result;
        List<Fragment> fragments=new ArrayList<>();
        List<String> titles=new ArrayList<>();
        for ( int i = 0 ; i < mData.size() ; i++){
            //获取标题name
            Title title=mData.get(i);
            titles.add(title.getName());
            //带内容页的Url新建fragment，添加到fragments
            Bundle bundle=new Bundle();
            bundle.putInt("contentId",title.getId());
            ContentFragment fragment=new ContentFragment();
            fragment.setArguments(bundle);
            fragments.add(fragment);
        }

        //设置适配器
        mVp.setAdapter(new MyVpAdapter(getSupportFragmentManager(),fragments, titles));

        //设置TabStrip
        tabs.setViewPager(mVp);//关联适配器
        tabs.setBackgroundColor(Color.parseColor(customColor));
        tabs.setIndicatorHeight(5);//滑动条高度
        tabs.setDividerColor(Color.parseColor(customColor));//分割线颜色
        tabs.setTextColor(Color.WHITE);//字体颜色
        tabs.setIndicatorColor(Color.WHITE);//滑动条颜色
    }

    //对抽屉进行操作
    private void initDrawer() {
        //Toolbar的基本设置以及开关
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setBackgroundColor(Color.parseColor(customColor));
        mToolbar.setTitle("美视");
        mToolbar.setTitleTextColor(Color.WHITE);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
        ActionBarDrawerToggle toggle=new ActionBarDrawerToggle(this,drawer,mToolbar,R.string.open,R.string.close);
        toggle.syncState();
        drawer.addDrawerListener(toggle);

        //抽屉内的ListView
        ListView drawer_lv = (ListView) findViewById(R.id.drawer_lv);
        List<Map<String,Object>> list=new ArrayList<>();
        String[] text=getResources().getStringArray(R.array.menu_text);
        int[] imgs=getResources().getIntArray(R.array.menu_imgs);
        //TODO:图片
        for ( int i = 0 ; i < text.length ; i++){
            Map<String,Object> map=new HashMap<>();
            map.put("text",text[i]);
            map.put("imgs",imgs[i]);
            list.add(map);
        }
        SimpleAdapter adapter=new SimpleAdapter(this,list,R.layout.menu_item,new String[]{"imgs","text"},new int[]{R.id.img_dw,R.id.tv_dw});
        drawer_lv.setAdapter(adapter);
        drawer_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                switch (position){
                    case 1://收藏页
                        startActivity(new Intent(MainActivity.this,CollectItem.class));
                        overridePendingTransition(0,0);
                        break;
                    case 5://退出登录
                        SharedPreferences name = getSharedPreferences("name", MODE_PRIVATE);
                        String username = name.getString("name", null);
                        if (username!=null){
                            SharedPreferences.Editor editor = name.edit();
                            editor.putString("name",null).commit();
                            hasLogin();
                        }else{
                            Toast.makeText(MainActivity.this, "您还没登录呢", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        });
    }

    //注册按钮点击事件
    public void register_dw(View view) {
        startActivity(new Intent(this,Register.class));
        overridePendingTransition(0,0);
    }

    //登录按钮点击事件
    public void login_dw(View view) {
        startActivity(new Intent(this,Login.class));
        overridePendingTransition(0,0);
    }

}
